package org.finesys.ai.service.impl;

import cn.hutool.core.io.FileTypeUtil;
import lombok.RequiredArgsConstructor;
import org.finesys.ai.entity.AigcOss;
import org.finesys.ai.mapper.AigcOssMapper;
import org.finesys.ai.service.AigcOssService;
import org.finesys.common.file.client.FileTemplate;
import org.finesys.common.file.properties.FileProperties;
import org.finesys.common.mp.core.service.impl.BaseServiceImpl;
import org.finesys.common.security.core.util.SecurityUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Service
@RequiredArgsConstructor
public class AigcOssSericeImpl extends BaseServiceImpl<AigcOssMapper, AigcOss> implements AigcOssService {

    private final FileTemplate fileTemplate;
    private final FileProperties fileProperties;

    @Override
    public boolean upload(MultipartFile file) throws Exception {
        String fileName = file.getOriginalFilename();
        fileTemplate.putObject(fileProperties.getBucketName(), fileName, file.getInputStream());
        this.save(buildAigcOss(file));
        return true;
    }

    private AigcOss buildAigcOss(MultipartFile file) throws IOException {
        Long userId = SecurityUtils.getUser().getUserId();
        AigcOss aigcOss = new AigcOss();
        aigcOss.setUserId(String.valueOf(userId));
        aigcOss.setOssId(fileProperties.getOss().getAppId());
        aigcOss.setOssUrl(fileProperties.getOss().getEndpoint());
        aigcOss.setBucketName(fileProperties.getBucketName());
        aigcOss.setFileName(file.getName());
        aigcOss.setOriginalFileName(file.getOriginalFilename());
        aigcOss.setFileSize(file.getSize());
        aigcOss.setFileType(FileTypeUtil.getType(file.getInputStream()));
        aigcOss.setContentType(file.getContentType());
        aigcOss.setPath(String.format("%s/%s", fileProperties.getBucketName(), aigcOss.getFileName()));
        return aigcOss;
    }
}
